<template>
  <div>
    <div class="header">
      <el-breadcrumb separator-class="el-icon-arrow-right">
        <el-breadcrumb-item :to="{ path: '/home/overallDisplay' }"
        >首页</el-breadcrumb-item
        >
        <el-breadcrumb-item>权限</el-breadcrumb-item>
        <el-breadcrumb-item>用户列表</el-breadcrumb-item>
      </el-breadcrumb>
    </div>
    <div class="search">
      <el-form :inline="true" :model="formInline" class="demo-form-inline">
        <el-form-item label="输入搜索">
          <el-input v-model="formInline.idOrName" placeholder="请输入编号或用户名"></el-input>

        </el-form-item>
        <el-form-item>

          <el-button icon="el-icon-search" @click="onsubmit">搜索</el-button>

          <el-button @click="resetForm()">重置</el-button>
        </el-form-item>
      </el-form>
    </div>
    <div class="add">
      <i class="el-icon-s-order" style="float: left;"><span>数据列表</span></i>
      <el-button style="float: right;" @click="dialogTableVisible = true"
      >增加</el-button
      >
      <el-dialog
          title="添加用户"
          :visible.sync="dialogTableVisible"
          :lock-scroll="false"
          :modal="false">
        <el-form :model="addform" :rules="rules" ref="ruleForm">
          <el-form-item
              label="用户名"
              prop="name"
              :label-width="formLabelWidth">
            <el-input v-model="addform.name" autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item
              label="密码"
              prop="password"
              :label-width="formLabelWidth">
            <el-input v-model="addform.password" autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item label="邮箱" :label-width="formLabelWidth">
            <el-input v-model="addform.email" autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item label="是否启用" :label-width="formLabelWidth">
            <el-radio v-model="addform.status" label="1">是</el-radio>
            <el-radio v-model="addform.status" label="0">否</el-radio>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="cancel('ruleForm')">取消</el-button>
          <el-button type="primary" @click="adduser('ruleForm')"
          >确定</el-button
          >
        </div>
      </el-dialog>
    </div>
    <div class="form">
      <el-table :data="tableData" border style="width: 100%" height="400">
        <el-table-column fixed prop="id" label="编号" min-width="150">
        </el-table-column>
        <el-table-column prop="name" label="姓名" min-width="120">
        </el-table-column>
        <el-table-column prop="code" label="权限码" min-width="120">
        </el-table-column>
        <el-table-column prop="email" label="邮箱" min-width="120">
        </el-table-column>
        <el-table-column prop="created" label="添加时间" min-width="300">
        </el-table-column>
        <el-table-column prop="lastLogin" label="登录时间" min-width="120">
        </el-table-column>
        <el-table-column label="是否启用" min-width="120">
          <template slot-scope="scope">
            <el-switch v-model="scope.row.isEnabled" :active-value="1" :inactive-value="0" active-color="#13ce66"
              inactive-color="#ff4949" @change="handleSwitchChange(scope.row)">
            <el-switch
                v-model="scope.row.isEnabled"
                :active-value="1"
                :inactive-value="0"
                active-color="#13ce66"
                inactive-color="#ff4949"
                @change="handleSwitchChange(scope.row)">
            </el-switch>
            </el-switch>
          </template>
        </el-table-column>
        <el-table-column fixed="right" label="操作" min-width="150">
          <template slot-scope="scope">
            <el-button type="text" size="small" @click="showid(scope.row.id)">分配用户</el-button>
            <el-dialog title="分配用户" :visible.sync="userDialogVisible" :lock-scroll="false" :modal="false">
              <el-form :model="userForm">
                <el-form-item label="选择用户">
                  <el-select v-model="userForm.selectedUser" placeholder="请选择用户">
                    <el-option v-for="role in roles" :key="role.id" :label="role.name" :value="role.id">
                    </el-option>
                  </el-select>
                </el-form-item>
              </el-form>
              <div slot="footer" class="dialog-footer">
                <el-button @click="userDialogVisible = false">取消</el-button>
                <el-button type="primary" @click="handleAssignUser()"
                >确定</el-button
                >
              </div>
            </el-dialog>

            <el-button type="text" @click="editUser(scope.row)">编辑</el-button>
            <el-dialog title="编辑用户" :visible.sync="editTableVisible" :lock-scroll="false" :modal="false">
              <el-form :model="editform">
                <el-form-item label="用户名" :label-width="formLabelWidth">
                  <el-input
                      v-model="editform.name"
                      autocomplete="off"></el-input>
                </el-form-item>
                <el-form-item label="权限码" :label-width="formLabelWidth">
                  <el-input
                      v-model="editform.code"
                      autocomplete="off"></el-input>
                </el-form-item>
                <el-form-item label="邮箱" :label-width="formLabelWidth">
                  <el-input
                      v-model="editform.email"
                      autocomplete="off"></el-input>
                </el-form-item>
                <el-form-item label="是否启用" :label-width="formLabelWidth">
                  <el-radio v-model="editform.status" label="1">是</el-radio>
                  <el-radio v-model="editform.status" label="0">否</el-radio>
                </el-form-item>
              </el-form>
              <div slot="footer" class="dialog-footer">
                <el-button @click="editTableVisible = false">取消</el-button>
                <el-button type="primary" @click="updateUser">确定</el-button>
              </div>
            </el-dialog>

            <el-button type="text" @click="showDeleteDialog(scope.row.id)">删除</el-button>
            <!-- <el-dialog title="提示" :visible.sync="delVisible" width="30%" :before-close="handleClose"
              :lock-scroll="false" :modal="false">
              <span>是否删除用户</span>
              <span slot="footer" class="dialog-footer">
                <el-button @click="delVisible = false">取 消</el-button>
                <el-button type="primary" @click="handleDeleteConfirm()"
                >确 定</el-button
                >
              </span>
            </el-dialog> -->
          </template>
        </el-table-column>
      </el-table>
      <div class="block">
        <el-pagination
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="currentPage4"
            :page-sizes="[5, 10, 20, 30]"
            :page-size="pageSize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total">
        </el-pagination>
      </div>
    </div>
  </div>
</template>

<script>
import axios from 'axios';

export default {
  name: "UserList",
  data() {
    var validateName = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('用户名不能为空'));
      } else if (typeof value !== 'string') {
        callback(new Error('用户名必须是字符串'));
      } else {
        callback();
      }
    };
    var validatePassword = (rule, value, callback) => {
      // 检查密码是否为空
      if (!value) {
        callback(new Error('密码不能为空'));
      }
      // 检查密码长度
      else if (value.length < 8) {
        callback(new Error('密码长度至少为8个字符'));
      }
      // 检查是否包含大写字母
      else if (!/[A-Z]/.test(value)) {
        callback(new Error('密码必须包含至少一个大写字母'));
      }
      // 检查是否包含小写字母
      else if (!/[a-z]/.test(value)) {
        callback(new Error('密码必须包含至少一个小写字母'));
      }
      // 验证通过
      else {
        callback();
      }
    };

    return {
      userForm: {
        selectedUser: ''
      },
      rules:{
        name:[{validator: validateName,trigger: 'blur'}],
        password:[{validator: validatePassword,trigger: 'blur'}]
      },
      roles: [],
      formInline: {
        idOrName: ''
      },
      roleDialogVisible: false,
      visible: false,
      currentPage4: 1,
      pageSize: 5,
      total: 0,
      tableData: [],
      userNumber: [],
      dialogTableVisible: false,
      dialogFormVisible: false,
      editTableVisible: false,
      delVisible: false,
      selectedId: null,
      radio: '1',
      addform: {
        name: '',
        password: '',
        email: '',
        status: '1'
      },
      editform: {
        id: '',
        name: '',
        password: '',
        email: '',
        status: '1'
      },
      formLabelWidth: '120px',
      userDialogVisible: false,
    }
  },

  mounted() {
    this.fetchUserList();
    this.fetchRoles();
  },
  methods: {
    cancel(formName){
      this.$refs[formName].resetFields();
      this.dialogTableVisible = false;
    },

    fetchUserList() {
      axios.get('http://localhost:8080/home/userList')
          .then(response => {
            console.log('获取用户列表成功:', response.data);
            const allUserData = response.data.data.userList.map(user => ({
              id: user.id,
              name: user.name,
              email: user.email,
              code: user.code,
              city: user.city,
              created: user.created,
              updated: user.updated,
              lastLogin: user.lastLogin,
              avatar: user.avatar,
              addtime: user.updated,
              isEnabled: user.status,
              userDialogVisible: false
            }));
            const allCodeKV = response.data.data.urList;
            allUserData.forEach(user => {
                  const nameReloKV = allCodeKV.find(item => item.userName === user.name);
                  if (nameReloKV) {
                    user.code = nameReloKV.roleName;
                  }
                }
            )

          const startIndex = (this.currentPage4 - 1) * this.pageSize;
          const endIndex = startIndex + this.pageSize;
          this.tableData = allUserData.slice(startIndex, endIndex);
          this.total = response.data.data.userList.length;
          console.log(this.total);
        })
        .catch(error => {
          console.error('获取用户列表失败:', error);
        });
    },
    fetchUserNumbers() {
      axios.get('http://localhost:8080/home/userList')
        .then(response => {
          console.log('获取到的用户数量数据:', response.data);
          if (response.data && response.data.data && response.data.data.userNumber) {
            this.userNumber = response.data.data.userNumber;
            this.mergeUserCounts();
          } else {
            console.warn('响应数据中未找到 userNumber 字段');
            this.userNumber = [];
          }
        })
        .catch(error => {
          console.error('获取用户数量失败:', error);
        });
    },
    mergeUserCounts() {
      const userNumberMap = this.userNumber.reduce((acc, item) => {
        const [userName, count] = Object.entries(item)[0];
        acc[userName] = count;
        return acc;
      }, {});

      this.tableData = this.tableData.map(user => ({
        ...user,
        userCount: userNumberMap[user.name] || 0
      }))
    },

    /**
     * 查询用户
     * */
    onsubmit() {
      const {idOrName} = this.formInline;
      const currentPage = this.currentPage4;
      if (!idOrName || idOrName.trim() === '') {
        this.$message.warning('请输入有效的搜索条件'); // 提示用户输入条件
        return; // 直接返回，不执行后续逻辑
      } else {

        console.log(idOrName);
      }


      axios.post("http://localhost:8080/home/queryUser", null, {
        params: {
          idOrName: idOrName
        }
      }).then(response => {
        console.log('搜索成功:', response.data);
        if (response.data.code === 20000 && response.data.data.queryUser) {
          let queryUser = response.data.data.queryUser;
          queryUser.code = response.data.data.codeOfUser; // 权限码在这里加进去
          if (!Array.isArray(queryUser)) {
            queryUser = [queryUser];
          }
          this.total = queryUser.length;
          console.log(this.total);
          const totalPages = Math.ceil(this.total / this.pageSize);
          if (currentPage > totalPages) {
            this.currentPage4 = totalPages || 1;
          } else {
            this.currentPage4 = currentPage;
          }
          this.tableData = queryUser.map(user => ({
            id: user.id,
            name: user.name,
            code:response.data.data.codeOfUser,
            email: user.email,
            city: user.city,
            created: user.created,
            updated: user.updated,
            lastLogin: user.lastLogin,
            avatar: user.avatar,
            isEnabled: user.status,
            userDialogVisible: false
          })), this.$message({
            message: '搜索成功',
            type: 'success'
          }),
            this.fetchUserNumbers();
        } else {
          this.tableData = [];
          this.$message.error('未找到相关用户');
          this.currentPage4 = 1;
        }
      })
          .catch(error => {
            console.error('搜索失败:', error);
            this.$message.error('搜索失败，请重试');
          });
    },
    resetForm() {
      this.formInline.idOrName = '';
      this.tableData = this.fetchUserList();
      this.currentPage4 = 1;

    },
    handleSwitchChange(row) {
      console.log(row.isEnabled)
      const id = row.id
      const isEnabled = row.isEnabled
      axios.post("http://localhost:8080/home/updatedUserStatus", {
            "status": isEnabled,
            "id": id
          }
      ).then((res) => {
        console.log(res)
      })
    },
    handleSizeChange(size) {
      this.pageSize = size;
      this.currentPage4 = 1;
      this.fetchUserList();
    },
    handleCurrentChange(page) {
      this.currentPage4 = page;
      this.fetchUserList();
    },

    handleClose(done) {
      this.$confirm('确认关闭？')
        .then(() => {
          done();
        })
        .catch(() => { });
    },
    resetAddForm() {
      this.addform.name = '';
      this.addform.password = '';
      this.addform.email = '';
      this.addform.status;
    },

    adduser(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          console.log('添加用户:', this.addform);

          // 验证邮箱格式
          const emailRegex = /^[^\s@]+@[a-zA-Z0-9-]+(\.[a-zA-Z0-9-]+)*\.[a-zA-Z]{2,}$/;
          if (!emailRegex.test(this.addform.email)) {
            this.$message.error('邮箱格式不正确，请输入有效的邮箱地址');
            return; // 中断操作
          }

      console.log(this.addform.name)
      // 发送请求到后端
      axios.post('http://localhost:8080/home/addUser', {
        "name": this.addform.name,
        "password": this.addform.password,
        "email": this.addform.email,
        "status": this.addform.status
      })
        .then(response => {
          console.log('添加用户成功:', response.data);
              this.$message.success('添加用户成功');
              this.fetchUserList();
              // 刷新表单内容
              this.resetAddForm();
              // 关闭对话框
            })
            .catch(error => {
              console.error('添加用户失败:', error);
            });
            this.dialogTableVisible = false;
          console.log(this.addform.name);

          // 发送请求到后端
          axios.post('http://localhost:8080/home/addUser', {
            "name": this.addform.name,
            "password": this.addform.password,
            "email": this.addform.email,
            "status": this.addform.status
          })
              .then(response => {
                console.log('添加用户成功:', response.data);
                this.$message.success('添加用户成功');
                this.fetchUserList();
                // 刷新表单内容
                this.resetAddForm();
                // 关闭对话框
                this.dialogTableVisible = false;
              })
              .catch(error => {
                console.error('添加用户失败:', error);
              });
        } else {
          console.log('error submit!!!');
          return false;
        }
      });
    },
    editUser(row) {
      this.editform = {
        id: row.id,
        name: row.name,
        password: row.password,
        email: row.email,

        status: row.isEnabled ? '1' : '0'
      };
      this.editTableVisible = true;
    },
    updateUser() {
      console.log('更新用户:', this.editform);
      // 发送请求到后端
      axios.post('http://localhost:8080/home/updatedUser', {
        "id": this.editform.id,
        "name": this.editform.name,
        "password": this.editform.password,
        "email": this.editform.email,
        "status": this.editform.status
      }
    )
        .then(response => {
          console.log('更新用户成功:', response.data);
          this.fetchUserList();
        })
        .catch(error => {
          console.error('更新用户失败:', error);
        });


      // 关闭对话框
      this.editTableVisible = false;
    },
    showDeleteDialog(id) {
      this.selectedId = id;
      console.log('删除用户:', id);
      this.$confirm('确定要删除选中的项目吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'error'
      }).then(() => {
        this.selectedId = id;
        this.handleDeleteConfirm()
        this.fetchUserList()
        this.$message({
          type: 'success',
          message: `成功删除一项`
        });

      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
      // this.delVisible = true;
    },
    handleDeleteConfirm() {
      // this.delVisible = false;
      // 发送删除请求
      axios.post('http://localhost:8080/home/deleteUser', null, { params: { id: this.selectedId } })
        .then(response => {
          console.log('删除成功:', response.data);
          this.fetchUserList(); // 再次获取用户列表

          // this.$message({
          //   message: '删除成功',
          //   type: 'success'
          // });
          // 重新获取用户列表
        //   this.fetchUserList().then(() => {
        //     if (this.tableData.length === 0 && this.currentPage4 > 1) {
        //       this.currentPage4--; // 如果当前页面无数据，且不在第一页，则回退到上一页
        //     }
        //   });
        })        // .catch(error => {
        //   console.error('删除失败:', error);
        //   this.$message.error('删除失败');
        // });
    },
    fetchRoles() {
      axios.get('http://localhost:8080/home/userAddRole')
        .then(response => {
          console.log('获取用户列表成功:', response.data);
          this.roles = response.data.data.optionalRole.map(roleName => ({
            id: roleName,
            name: roleName
          }));
        })
        .catch(error => {
          console.error('获取用户列表失败:', error);
        });
    },
    showid(id) {
      this.selectedId = id;
      console.log('查看用户id:', id);
      this.userDialogVisible = true
    },
    handleAssignUser() {
      const selectedUserId = this.selectedId;
      const selectedRoleId = this.userForm.selectedUser;

      if (!selectedUserId || !selectedRoleId) {
        this.$message.error('请选择用户和用户');
        return;
      }

      console.log('用户ID:', selectedUserId);
      console.log('用户名称:', this.roles.find(role => role.id === selectedRoleId).name);
      const roleName = this.roles.find(role => role.id === selectedRoleId).name;
      console.log('返回的数据:', { userId: selectedUserId, roleName: roleName });
      axios.post('http://localhost:8080/home/userRole',{
        "userId": selectedUserId,
        "roleName": roleName,
      }).then(response => {
          console.log('更新用户成功:', response.data);
          this.fetchUserList();
           // 关闭对话框
          this.userDialogVisible = false;
        })
        .catch(error => {
          console.error('更新用户失败:', error);
        });
      // 关闭对话框
      this.userDialogVisible = false;
    }


  }
}


</script>

<style scoped>
.form {
  width: 100%;
  overflow-x: auto;
}

.el-table {
  margin-bottom: 20px;
}

.header {
  width: 100%;
  padding-bottom: 20px;
}

.search {
  width: 100%;
  padding-bottom: 20px;
}

.demo-form-inline {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.button-group {
  display: flex;
  gap: 5px;
}

.add {
  width: 100%;
  padding-bottom: 20px;
  overflow: hidden;
}

.block {
  margin-top: 20px;
}
</style>
